package com.huyu.substat.modules.substat.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.easy.excel.ExcelImport;
import org.easy.excel.vo.ExcelDefinition;
import org.easy.excel.vo.ExcelImportResult;
import org.easy.excel.vo.FieldValue;
import org.springframework.web.context.WebApplicationContext;

public class FileImportService extends BaseSubjectService {
	private static final Logger logger = Logger.getLogger(FileImportService.class);

	public void importFile(String className, File excelFile, WebApplicationContext appContext) {
		this.appContext = appContext;
		try {
			Map<String, String> table = getTableMap(className);
			List<FieldValue> fieldValues = getFieldValues(className, table);

			// 准备excel文件流
			InputStream excelStream = new FileInputStream(excelFile);
			// 创建excel上下文实例,它的构成需要配置文件的路径
			ExcelImport excelImport = new ExcelImport(null);
			ExcelDefinition excelDefinition = new ExcelDefinition();
			excelDefinition.setClassName(className);

			excelDefinition.setFieldValues(fieldValues);

			Class clazz = Class.forName("com.huyu.substat.modules.substat.entity." + table.get("className"));
			excelDefinition.setClazz(clazz);

			int titleIndex = 0; // 没有表头，就从第0行开始
			ExcelImportResult importResult = excelImport.doReadExcel(excelDefinition, titleIndex, excelStream);
			logger.info(importResult.getListBean());
		} catch (Exception e) {
			logger.error("importFile error", e);
		}
	}
}
